import $ from 'jquery';
import _ from 'lodash';
import { transformToSelector } from '../shared/transformToSelector';
import { toast } from '../shared/toast';

const selector = transformToSelector(
  `py-2 pr-2 font-mono font-medium text-xs leading-6 text-sky-500 whitespace-nowrap dark:text-sky-400`,
);
function addCopyBtn() {
  $(selector).each((index, item) => {
    $(item)
      .addClass('select-none flex items-center')
      .prepend(
        `<btton class="px-2 cursor-pointer copy-button mr-1" data-text="${$(
          item,
        ).text()}">复制</btton>`,
      );
  });
}

function listenerCopyBtnClick() {
  $(document.body).on('click', `${selector} .copy-button`, (event) => {
    const t = $(event.currentTarget).data('text');
    navigator.clipboard.writeText(t);
    toast(`复制【${t}】成功 ✅`);
  });
}

function listenerMenuClick() {
  const throttledAddCopyBtn = _.throttle(addCopyBtn, 500);
  $('#nav').on('click', 'li', () => {
    throttledAddCopyBtn();
  });
}

function main() {
  addCopyBtn();
  listenerMenuClick();
  listenerCopyBtnClick();
}

$(main);
